package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.dto.RepairmanInfoDTO;
import com.qianying.entity.RepairmanInfo;
import com.qianying.entity.SysUser;
import com.qianying.entity.UserWorkType;
import com.qianying.mapper.RepairmanInfoMapper;
import com.qianying.service.ChinaAreaService;
import com.qianying.service.RepairmanInfoService;
import com.qianying.service.SysUserService;
import com.qianying.service.UserWorkTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 维修师傅信息Service实现类
 * 作者：check
 */
@Service
public class RepairmanInfoServiceImpl extends ServiceImpl<RepairmanInfoMapper, RepairmanInfo> implements RepairmanInfoService {

    @Autowired
    private RepairmanInfoMapper repairmanInfoMapper;
    @Autowired
    private ChinaAreaService chinaAreaService;
    @Autowired
    private UserWorkTypeService userWorkTypeService;
    @Autowired
    private SysUserService userService;

    @Override
    public CommonResult<RepairmanInfo> getById(Long id) {
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }

        RepairmanInfo repairmanInfo = baseMapper.selectById(id);
        if (repairmanInfo == null) {
            return CommonResult.failed("维修师傅不存在");
        }

        Map<Long, String> areaMap = chinaAreaService.IdToNameMap();

        if (areaMap.containsKey(repairmanInfo.getProvinceId())) {
            repairmanInfo.setProvinceName(areaMap.get(repairmanInfo.getProvinceId()));
        }
        if (areaMap.containsKey(repairmanInfo.getCityId())) {
            repairmanInfo.setCityName(areaMap.get(repairmanInfo.getCityId()));
        }

        if (areaMap.containsKey(repairmanInfo.getDistrictId())) {
            repairmanInfo.setDistrictame(areaMap.get(repairmanInfo.getDistrictId()));
        }

        return CommonResult.success(repairmanInfo);
    }

    @Override
    public CommonResult<?> saveRepairman(RepairmanInfo repairmanInfo, Long userId) {
        if (repairmanInfo == null) {
            return CommonResult.failed("保存的信息不能为空！");
        }
        if (userId == null) {
            return CommonResult.failed("没有获取到用户Id");
        }
        repairmanInfo.setUserId(userId);
        // 校验必填字段
        if (!StringUtils.hasText(repairmanInfo.getRealName())) {
            return CommonResult.failed("真实姓名不能为空");
        }
        if (!StringUtils.hasText(repairmanInfo.getIdCard())) {
            return CommonResult.failed("身份证号码不能为空");
        }

        // 校验身份证号唯一性
        LambdaQueryWrapper<RepairmanInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RepairmanInfo::getIdCard, repairmanInfo.getIdCard());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return CommonResult.failed("该身份证号码已注册");
        }
        repairmanInfo.setId(null);
        repairmanInfo.setCreateTime(LocalDateTime.now());
        repairmanInfo.setUpdateTime(LocalDateTime.now());

        boolean saveFlag = save(repairmanInfo);
        return saveFlag ? CommonResult.success(repairmanInfo,"新增成功") : CommonResult.failed("新增失败");
    }

    @Override
    public CommonResult<?> updateRepairman(RepairmanInfo repairmanInfo) {
        // 1. 校验ID
        if (repairmanInfo.getId() == null) {
            return CommonResult.failed("ID不能为空");
        }

        // 2. 检查维修师傅是否存在
        RepairmanInfo existing = baseMapper.selectById(repairmanInfo.getId());
        if (existing == null) {
            return CommonResult.failed("维修师傅不存在");
        }

        // 4. 构建动态更新条件（只更新非空字段）
        LambdaUpdateWrapper<RepairmanInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RepairmanInfo::getId, repairmanInfo.getId());

        // 真实姓名非空则更新
        if (StringUtils.hasText(repairmanInfo.getRealName())) {
            updateWrapper.set(RepairmanInfo::getRealName, repairmanInfo.getRealName());
        }

        // 身份证号非空则更新
        if (StringUtils.hasText(repairmanInfo.getIdCard())) {
            updateWrapper.set(RepairmanInfo::getIdCard, repairmanInfo.getIdCard());
        }

        // 身份证号非空则更新
        if (StringUtils.hasText(repairmanInfo.getIdCardFront())) {
            updateWrapper.set(RepairmanInfo::getIdCardFront, repairmanInfo.getIdCardFront());
        }

        // 身份证背面照片
        if (StringUtils.hasText(repairmanInfo.getIdCardBack())) {
            updateWrapper.set(RepairmanInfo::getIdCardBack, repairmanInfo.getIdCardBack());
        }

        // 地址非空则更新
        if (StringUtils.hasText(repairmanInfo.getAddress())) {
            updateWrapper.set(RepairmanInfo::getAddress, repairmanInfo.getAddress());
        }

        // 省份ID非空则更新
        if (repairmanInfo.getProvinceId() != null) {
            updateWrapper.set(RepairmanInfo::getProvinceId, repairmanInfo.getProvinceId());
        }

        // 城市ID非空则更新
        if (repairmanInfo.getCityId() != null) {
            updateWrapper.set(RepairmanInfo::getCityId, repairmanInfo.getCityId());
        }

        // 区/县ID非空则更新
        if (repairmanInfo.getDistrictId() != null) {
            updateWrapper.set(RepairmanInfo::getDistrictId, repairmanInfo.getDistrictId());
        }


        // 最后更新时间
        updateWrapper.set(RepairmanInfo::getUpdateTime, LocalDateTime.now());

        // 5. 执行更新
        int rows = baseMapper.update(null, updateWrapper);
        return rows > 0 ? CommonResult.success("更新成功") : CommonResult.failed("更新失败或数据未变化");
    }

    @Override
    public CommonResult<IPage<RepairmanInfoDTO>> getRepairmanPage(Integer pageNum, Integer pageSize, String realName,
                                                    String phone, Integer enableStatus, Long provinceId,
                                                    Long cityId, Long districtId, Long workTypeId) {

        // 1. 初始化分页对象
        Page<RepairmanInfo> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        LambdaQueryWrapper<RepairmanInfo> queryWrapper = new LambdaQueryWrapper<>();

        // 2.1 基础信息筛选（repairman_info表）
        if (StringUtils.hasText(realName)) {
            queryWrapper.like(RepairmanInfo::getRealName, realName);
        }
        if (provinceId != null) {
            queryWrapper.eq(RepairmanInfo::getProvinceId, provinceId);
        }

        // 2.2 关联用户表筛选（sys_user表）
        // phone字段在用户表，使用子查询实现手机号模糊查询
        if (StringUtils.hasText(phone)) {
            queryWrapper.inSql(RepairmanInfo::getUserId,
                    "SELECT id FROM sys_user WHERE phone LIKE '%" + phone + "%'");
        }

        // 启用状态在用户表，使用子查询筛选
        if (enableStatus != null) {
            queryWrapper.inSql(RepairmanInfo::getUserId,
                    "SELECT id FROM sys_user WHERE enable_status = " + enableStatus);
        }

        // 2.3 关联服务项目筛选（子查询）
        if (workTypeId != null) {
            queryWrapper.inSql(RepairmanInfo::getId,
                    "SELECT repairman_info_id FROM user_work_type WHERE work_type_id = " + workTypeId);
        }

        // 2.4 排序：按创建时间倒序
        queryWrapper.orderByDesc(RepairmanInfo::getCreateTime);

        // 3. 执行分页查询
        IPage<RepairmanInfo> repairmanPage = baseMapper.selectPage(page, queryWrapper);


        List<RepairmanInfoDTO> repairmanInfoDTOS = new ArrayList<>();
        // 执行分页查询
        if (!repairmanPage.getRecords().isEmpty()) {
            Map<Long, String> areaMap = chinaAreaService.IdToNameMap();
            for (RepairmanInfo record : repairmanPage.getRecords()) {

                RepairmanInfoDTO repairmanInfoDTO = new RepairmanInfoDTO();
                if (areaMap.containsKey(record.getProvinceId())) {
                    record.setProvinceName(areaMap.get(record.getProvinceId()));
                }

                if (areaMap.containsKey(record.getCityId())) {
                    record.setCityName(areaMap.get(record.getCityId()));
                }

                if (areaMap.containsKey(record.getDistrictId())) {
                    record.setDistrictame(areaMap.get(record.getDistrictId()));
                }
                repairmanInfoDTO.setRepairmanInfo(record);

                CommonResult<List<UserWorkType>> list = userWorkTypeService.getByUserId(record.getUserId());
                if (list.isSuccess()) {
                    repairmanInfoDTO.setUserWorkTypeList(list.getData());
                }

                SysUser user = userService.getById(record.getUserId());
                if (user != null) {
                    repairmanInfoDTO.setIsEnable(user.getEnabled());
                }
                repairmanInfoDTOS.add(repairmanInfoDTO);
            }
        }
        Page<RepairmanInfoDTO> resPage = new Page<>(repairmanPage.getCurrent(), repairmanPage.getPages());
        resPage.setRecords(repairmanInfoDTOS);

        return CommonResult.success(resPage);
    }
}
